const koa = require("koa");
const router = require("koa-router")();
const bodyParser = require("koa-bodyparser");
const cors = require("koa2-cors");
const app = new koa();
router.post("/login",async ctx=>{
    /* username=cheng,pass=123 */
    var {username,pass} = ctx.request.body;
    if(username=="cheng" && pass == "123"){
        ctx.cookies.set("loginAuth",true,{  //前后端都需要配置使跨域访问cookies
            httpOnly:false  //服务器端设置cookies使其可读
        })
        ctx.body= {
            code:200,
            auth:true,
            msg:"登录成功"
        }
    }else{
        ctx.body = {
            code:400,
            msg:"用户名或密码错误"
        }
    }
    
})
// router.get("/logout",async ctx=>{    //localhost:8000/logout
router.post("/logout",async ctx=>{
    ctx.cookies.set("loginAuth","");
    ctx.body = {
        code:200,
        msg:"退出登录"
    }
})
app.use(cors({
    // origin:"http://192.168.4.88:8080",//是说这个地址是可以跨域访问cookies的
    origin:ctx=>{
        // console.log(ctx.header.origin);
        return ctx.header.origin;//http://1localhost:8080
    },
    credentials:true
    //可以跨域访问cookie
}));
app.use(bodyParser());
app.use(router.routes());
app.listen(8000);